package com.demo.study.thread.compalteFuture;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class CompletableFutureExample1 {
    public static void main(String[] args) {
        CompletableFuture<List<String>> future1 = CompletableFuture.supplyAsync(() -> getList1());
        CompletableFuture<List<String>> future2 = CompletableFuture.supplyAsync(() -> getList2());

        CompletableFuture<List<String>> allFutures = CompletableFuture
                .allOf(future1, future2)
                .thenApply(Void -> Stream.of(future1.join(), future2.join())
                        .flatMap(List::stream)
                        .collect(Collectors.toList()));

        List<String> result = allFutures.join();
        System.out.println(result);
    }

    private static List<String> getList1() {
        // 模拟耗时操作
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return Arrays.asList("A", "B", "C");
    }

    private static List<String> getList2() {
        // 模拟耗时操作
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return Arrays.asList("D", "E", "F");
    }
}
